﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LabChecker.Models;
using LabChecker.Services;

namespace LabChecker.Controllers
{ 
    [Authorize]
    public class SubjectController : Controller
    {
        private LabCheckerContext db = new LabCheckerContext();

        public ViewResult Index()
        {
            return View(db.Subjects.ToList());
        }

        public ViewResult Details(int id)
        {
            Subject subject = db.Subjects.Find(id);
            return View(subject);
        }

        public ActionResult Create()
        {
            return View();
        } 

        [HttpPost]
        public ActionResult Create(Subject subject)
        {
            if (ModelState.IsValid)
            {
                db.Subjects.Add(subject);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(subject);
        }

        public ActionResult Import()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DoImport()
        {
            var file = Request.Files[0];
            var subject = SubjectImportService.Import(file.InputStream);

            if (TryValidateModel(subject))
            {
                db.Subjects.Add(subject);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View("Import");
        }
 
        public ActionResult Edit(int id)
        {
            Subject subject = db.Subjects.Find(id);
            return View(subject);
        }

        [HttpPost]
        public ActionResult Edit(int id, FormCollection formCollection)
        {
            var subject = db.Subjects.Find(id);

            if (TryUpdateModel(subject))
            {                
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(subject);
        }
 
        public ActionResult Delete(int id)
        {
            Subject subject = db.Subjects.Find(id);
            return View(subject);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Subject subject = db.Subjects.Find(id);
            db.Subjects.Remove(subject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}